package net.mingsoft.cms.job;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.io.FileUtil;
import net.mingsoft.cms.bean.CategoryBean;
import net.mingsoft.cms.bean.ContentBean;
import net.mingsoft.cms.biz.ICategoryBiz;
import net.mingsoft.cms.biz.IContentBiz;
import net.mingsoft.cms.constant.e.CategoryTypeEnum;
import net.mingsoft.cms.dao.IContentShuffleTagDao;
import net.mingsoft.cms.entity.CategoryEntity;
import net.mingsoft.cms.util.CmsParserUtil;
import net.mingsoft.mdiy.util.ParserUtil;

@Component
public class AutoGenerateJob {
	Logger logger = LoggerFactory.getLogger(AutoGenerateJob.class);
	@Value("${ms.diy.html-dir:html}")
    private String htmlDir;
	/**
     * 栏目管理业务层
     */
    @Autowired
    private ICategoryBiz categoryBiz;
    @Autowired
    private IContentBiz contentBiz;
    @Autowired
    private IContentShuffleTagDao tagdao;
	/**
	 * 定时静态化
	 */
	@Scheduled(cron="${ms.diy.gen-cron:'0 0 1 * * ?'}") //默认每天1:00分执行静态化
	public void generatePages() {
		logger.info("===================开始静态化=================");
		logger.info("===================静态化首页开始=================");
		// 模版文件名称
        String tmpFileName = "index.htm";
        // 生成后的文件名称
        String generateFileName = "index";
        // 获取文件所在路径 首先判断用户输入的模版文件是否存在
        if (FileUtil.exist(ParserUtil.buildTempletPath())) {
            try {
				CmsParserUtil.generate(tmpFileName, generateFileName,htmlDir);
				logger.info("===================静态化首页完毕=================");
			} catch (IOException e) {
				logger.info("===================静态化首页异常=================");
				e.printStackTrace();
			}
        }
        
        logger.info("===================静态化栏目开始=================");
      //栏目列表
        List<CategoryEntity> columns = new ArrayList<CategoryEntity>();
        CategoryEntity categoryEntity = new CategoryEntity();
        columns = categoryBiz.query(categoryEntity);

        //文章列表
        List<CategoryBean> articleIdList = null;

        // 获取栏目列表模版
        for (CategoryEntity column : columns) {

            ContentBean contentBean = new ContentBean();
            contentBean.setCategoryId(column.getId());

            articleIdList = contentBiz.queryIdsByCategoryIdForParser(contentBean);
            // 判断列表类型
            switch (CategoryTypeEnum.get(column.getCategoryType())) {
                case LIST: // 列表
                    // 判断模板文件是否存在
                    if (!FileUtil.exist(ParserUtil.buildTempletPath(column.getCategoryListUrl()))) {
                        logger.error("模板不存在：{}", column.getCategoryUrl());
                        continue;
                    }
                    try {
	                    if("rmbq".equals(column.getCategoryPinyin())) {
	                    	CmsParserUtil.generateList(column, tagdao.tagShuffCount(),htmlDir);
	                    }else {
	                    	CmsParserUtil.generateList(column, articleIdList.size(),htmlDir);
	                    }
		            } catch (IOException e) {
						logger.info("===================静态化栏目异常=================");
						e.printStackTrace();
					}
                    break;
                case COVER:// 单页
                    if (articleIdList.size() == 0) {
                        CategoryBean columnArticleIdBean = new CategoryBean();
                        CopyOptions copyOptions = CopyOptions.create();
                        copyOptions.setIgnoreError(true);
                        BeanUtil.copyProperties(column, columnArticleIdBean, copyOptions);
                        articleIdList.add(columnArticleIdBean);
                    }
                    CmsParserUtil.generateBasic(articleIdList,htmlDir);
                    break;
            }
        }
        
        logger.info("===================静态化栏目结束=================");
        logger.info("===================静态化文章开始=================");
        String dateTime = "2020-01-01";//文章检索开始
        // 网站风格物理路径
        articleIdList = null;
        List<CategoryEntity> categoryList = new ArrayList<CategoryEntity>();
        ContentBean contentBean = new ContentBean();
        contentBean.setBeginTime(dateTime);

        // 生成所有栏目的文章
        categoryList = categoryBiz.list(Wrappers.<CategoryEntity>lambdaQuery()
                .isNull(CategoryEntity::getCategoryParentIds));

        for (CategoryEntity category : categoryList) {
            contentBean.setCategoryId(category.getId());
            //将文章列表标签中的中的参数
            articleIdList = contentBiz.queryIdsByCategoryIdForParser(contentBean);
            // 分类是列表
            if (category.getCategoryType().equals(CategoryTypeEnum.LIST.toString())) {
                // 判断模板文件是否存在
                if (!FileUtil.exist(ParserUtil.buildTempletPath(category.getCategoryListUrl())) || StringUtils.isEmpty(category.getCategoryListUrl())) {
                    logger.error("模板不存在：{}", category.getCategoryUrl());
                    continue;
                }
            } else if (category.getCategoryType().equals(CategoryTypeEnum.COVER.toString())) {
                CategoryBean columnArticleIdBean = new CategoryBean();
                CopyOptions copyOptions = CopyOptions.create();
                copyOptions.setIgnoreError(true);
                BeanUtil.copyProperties(category, columnArticleIdBean, copyOptions);
                articleIdList.add(columnArticleIdBean);
            }
            // 有符合条件的就更新
            if (articleIdList.size() > 0) {
                CmsParserUtil.generateBasic(articleIdList,htmlDir);
            }
        }
        logger.info("===================静态化文章结束=================");
	}
}
